from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from goods.models import Carousel,Category,Goods,GoodImg,GoodsCollect
from user.models import User
from goods.serializer import CarouselSer,GoodsSer,CategorySer,GoodImgSer,GoodsCollectSer
from functools import reduce
from rest_framework.pagination import PageNumberPagination
from rest_framework.generics import ListAPIView
from rest_framework_jwt.utils import jwt_decode_handler
import redis

from django.http import JsonResponse
# from haystack.views import SearchView

# Create your views here.
# 轮播图
class CarouselView(APIView):
    def post(self,request):
        carousel = Carousel.objects.all()
        ser = CarouselSer(carousel,many=True)
        return Response(ser.data)

# 商品列表
class GoodsCateName(APIView):
    def post(self,request):
        catename = request.data.get('categoryName')
        cate = Category.objects.get(cate_name=catename)
        goods = cate.goods_set.all()
        ser = GoodsSer(goods,many=True)
        return Response(ser.data)

# 热门商品
class HotGoodsView(APIView):
    def post(self,request):
        catename = request.data.get('categoryName')

        category = []
        for name in catename:
            category.append(Category.objects.get(cate_name=name))

        goods = []
        for name in category:
            goods.append(name.goods_set.all())

        res = reduce(lambda x,y:x|y,goods).order_by('-count')
        ser = GoodsSer(res,many=True)
        return Response(ser.data)

# 获取所有类别
class CategoryView(APIView):
    def post(self,request):
        cate = Category.objects.all()
        ser = CategorySer(cate,many=True)
        return Response(ser.data)

# 根据类别ID获取所有商品
class GoodCategoryView(APIView):
    def get(self,request):
        cateID = request.query_params['categoryID']
        try:
            cate = Category.objects.get(id=cateID)
        except Exception as e:
            return Response({'msg':'没有此类别'})
        goods = cate.goods_set.all()
        ser = GoodsSer(goods,many=True)
        return Response(ser.data)

# 分页器
class Pagination(PageNumberPagination):
    page_size = 7
    page_size_query_param = 'pageSize'
    page_query_param = 'page'

# 获取所有商品
class GoodAllView(ListAPIView):
    queryset = Goods.objects.all()
    serializer_class = GoodsSer
    pagination_class = Pagination

# 商品图片
class GoodsImgView(APIView):
    def get(self,request):
        gid = request.query_params.get('productID')
        if gid:
            try:
                Goodsid = Goods.objects.get(id=gid)
            except Exception as e:
                return Response({'msg':'没有此商品'})
            img = Goodsid.goodimg_set.all()
            ser = GoodImgSer(img, many=True)
            return Response(ser.data)
        else:
            return Response({'msg':'商品id获取错误'})

# 商品详情
class GoodsDetailView(APIView):
    def get(self,request):
        gid = request.query_params.get('productID')
        if gid:
            try:
                good = Goods.objects.get(id=gid)
            except Exception as e:
                return Response({'msg':'没有此商品'})
            ser = GoodsSer(good)
            return Response(ser.data)
        else:
            return Response({'msg':'商品id获取错误'})

# 历史记录
class AddHistory(APIView):
    def post(self,request):
        gid = request.data.get('productID')
        token = request.data.get('token')
        if not token:
            return Response({'msg':'请先登录','code':400})
        else:
            payload = jwt_decode_handler(token)
            print('>>>>>>>>>>>>>',payload)
            user_id = payload.get('user_id')
            redis_cli = redis.Redis(password='123456')
            history = 'history_%s'%user_id
            redis_cli.lrem(history,0,gid)
            redis_cli.lpush(history,gid)
            redis_cli.close()
            return Response({'msg':'添加历史浏览记录成功','code':200})

# 收藏商品
class CollectView(APIView):
    def post(self,request):
        user = request.data.get('user')
        product_id = request.data.get('product_id')
        print('>>>>>>>>>>>>>>>>',user)
        print('>>>>>>>>>>>>>>>>',product_id)
        if not user:
            return Response({'msg':'获取用户信息错误','code':400})
        if not product_id:
            return Response({'msg':'获取商品信息错误','code':400})
        try:
            dict_user = User.objects.get(username=user['userName'])
        except Exception as e:
            return Response({'msg':'没有此用户','code':400})
        try:
            goods = Goods.objects.get(id=product_id)
        except Exception as e:
            return Response({'msg':'没有此商品','code':400})
        if GoodsCollect.objects.filter(goods_id=product_id).count() > 0:
            return Response({'msg':'商品已存在'})
        good = GoodsCollect.objects.create(user=dict_user,goods=goods)
        ser = GoodsCollectSer(good)
        return Response({'msg':'添加收藏成功','code':200,'data':ser.data})

# 查看收藏
class CollectInfoView(APIView):
    def post(self,request):
        dict_user = request.data.get('user')
        token = request.data.get('token')
        if not all([dict_user,token]):
            return Response({'msg':'请先登录！','code':400})
        try:
            user = User.objects.get(username=dict_user['userName'])
        except Exception as e:
            return Response({'msg':'没有此用户','code':400})
        payload = jwt_decode_handler(token)
        user_id = payload.get('user_id')
        if user_id == user.id:
            products = user.goodscollect_set.all()
            collect_goods = []
            for product in products:
                collect_goods.append({
                    "id": product.goods.id,
                    'sku_name': product.goods.sku_name,
                    "price": product.goods.price,
                    "selling_price": product.goods.selling_price,
                    "img": product.goods.img,
                    "title": product.goods.title,
                    "instruction": product.goods.instruction
                })
            return Response({'msg':'ok','code':200,'data':collect_goods})
        else:
            return Response({'msg':'用户信息错误','code':400})

# 删除收藏
class CollectDelView(APIView):
    def delete(self,request):
        dict_user = request.data.get('user')
        product_id = request.data.get('product_id')
        try:
            user = User.objects.get(username=dict_user['userName'])
        except Exception as e:
            return Response({'msg':'没有此用户','code':400})
        GoodsCollect.objects.filter(goods_id=product_id,user_id=user.id).delete()
        return Response({'msg':'删除成功','code':200})

# 搜索
# class MySearchView(SearchView):
#     """自定义返回json"""
#     def create_response(self):
#         context = super().get_context()
#         # print(">>>context", context)
#         # 获取当前的分页
#         current_page = context.get("page")
#         # 查询结果的分页
#         goods_list = []
#         # print('商品列表>>',current_page.object_list )
#         for i in current_page.object_list:
#             # 将每一个商品对象放入列表
#             goods_list.append(i.object)
#         # 对商品列表序列化
#         goods_ser = GoodsSer(goods_list, many=True)
#
#         # 返回响应
#         return JsonResponse({
#             "code": 200,
#             "msg": "查询商品成功！",
#             "product": goods_ser.data,
#             "total": len(goods_list)
#         })